<?php 
	require_once  __DIR__."/../silex/vendor/autoload.php";
	require_once  __DIR__."/Helpers/session.php";
	require_once  __DIR__."/Helpers/connection.php";
	require_once  __DIR__."/Helpers/pict.php";
	
	use Helpers\Session;
	use Helpers\Pict;
	
	use Symfony\Component\HttpFoundation\Request;
	use Symfony\Component\HttpFoundation\Response;
	

	$app = new Silex\Application();
	$app['debug']=true;
	$app->register(new Silex\Provider\DoctrineServiceProvider(), Helpers\Connection\getCon('local'));
	$app->register(new Silex\Provider\SessionServiceProvider());
	$app->register(new Silex\Provider\TwigServiceProvider(), array(
	    'twig.path' => __DIR__.'/../views',
	));
	$app->register(new Silex\Provider\UrlGeneratorServiceProvider());
	$app->register(new Silex\Provider\HttpFragmentServiceProvider() );
	
	//validators	
	$pdo = new PDO('mysql:dbname=forge', 'root', 'mysql');
	$app['fpdo'] = new FluentPDO($pdo);


	$app['pict'] = new Pict\PictManipulation($app);

	$app['controllers']
		->before(function() use ($app) {
			if( !$app['session']->has('uid') ){
				Session\session_init($app);	
			}	

			$uid = 	$app['session']->get('uid');
			$sid = $app['session']->getid();
			$app['session']->set('uid',1);

			$sql_exist = 'SELECT COUNT(*) count FROM session WHERE session_id = ?';
			$res_exist = $app['db']->fetchAssoc($sql_exist, array( (string) $sid ));
			//echo "count ". $res_exist['count']. "<br>";
			
			if($res_exist['count'] == 0){
				$app['db']->delete( 'session', array( 'session_id' => $sid) );
				Session\session_init($app);	
			}



			if($app['session']->get('REMOTE_ADDR') != $_SERVER['REMOTE_ADDR']){
				$app['db']->delete( 'session', array( 'session_id' => $sid) );
				Session\session_init($app);		
			}

			if($uid > 0){
				$sql = "SELECT TIME_TO_SEC(TIMEDIFF(now(),session_time))/60 time FROM `session` WHERE session_id = ? ";
				//echo "sql $sql <br>";
				$res = $app['db']->fetchAssoc($sql, array( (string) $sid ));
				//echo "time {$res['time']} <br>";
				if(	  $res['time'] > 60  ){
				//	echo ">0 <br>";
					//Session\session_destroy($app);	
					$app['db']->delete( 'session', array( 'session_id' => $sid) );
					Session\session_init($app);	
					//Session\session_update($app);
				}else{
				//	echo "<60  <br>";
					Session\session_update($app);
				}
			}
		});
	
	$app['homepage_route'] = Helpers\Connection\getHomeRoute('local');

	/**
		->before(function() use ($app){
			$uid = $app['session']->get('uid');
			if($uid == 0){
				return $app->redirect($app['url_generator']->generate('login'));
			}
		})
	*/


	$app->get('/', function() use ($app) {
		return $app['twig']->render('index.html', array("base_url"=>$app['homepage_route']));
	})
	->bind('homepage');

	
	$app->get('/login', function() use ($app) {
		return $app['twig']->render('login.html');
	})->bind("login");

	$app->get('/logout', function() use ($app){
		
		$sid = $app['session']->getId();
		$app['db']->delete( 'session', array( 'session_id' => $sid) );
		Session\session_init($app);
		return $app->redirect($app['url_generator']->generate('homepage'));

	});

	$app->post('/login', function(Request $request) use ($app){
		$login = '';
		$pass = '';
		$login = $request->get('login');
		$pass = $request->get('password');

		$sql = 	"SELECT iduser user_id FROM  user WHERE user_login = ? AND	 user_pass = md5( ? )";
		$res = $app['db']->fetchAssoc($sql, array( (string) $login, (string) $pass ) );

		/*
		echo "$login $pass $sql <br>";
		echo json_encode( $res ) . "<br>";*/

		if( !$res ){
			return '';
		}else{

			$uid = $res['user_id'];
			$sql = 	"SELECT usersetting_role role, usersetting_display_name display_name FROM  user_setting WHERE user_id = ?";
			$res_setting = $app['db']->fetchAssoc($sql, array(  (int) $uid ) );			
			$app['session']->set('uid',$res['user_id']);
			$app['session']->set('REMOTE_ADDR',$_SERVER['REMOTE_ADDR']);
			
			/*echo  json_encode( $res_setting ) ."<br>";*/

			if($res_setting){
				$user_var['role'] = $res_setting['role'];
				$user_var['display_name'] = $res_setting['display_name'];		
			}else{
				$user_var['role'] = 6;
				$user_var['display_name'] = '';		
			}
			
			/*echo  json_encode( $user_var ) ."<br>";*/
			$app['session']->set('user_var',$user_var);
			Session\session_update($app);
			/*echo  json_encode($app['session']->get('user_var')) ."<br>";*/
			/*echo  $app['session']->get('uid') ."<br>";
			return 'root';*/
				return $app->redirect($app['url_generator']->generate('homepage'));
		}
	});

	$app->get('/authcontrol',function() use ($app){
		$user_var = $app['session']->get('user_var');
		$base_url = $app['homepage_route'];
		return $app['twig']->render('authcontrol.html', array('user_var'=>$user_var, "base_url"=>$base_url));
	});





	$app->mount("/pics", include __DIR__."/Controllers/pics.php");
	$app->mount("/pic", include __DIR__."/Controllers/pic.php");
	$app->mount("/texts", include __DIR__."/Controllers/texts.php");
	$app->mount("/projects", include __DIR__."/Controllers/projects.php");
	$app->mount("/project", include __DIR__."/Controllers/project.php");
	$app->mount("/news", include __DIR__."/Controllers/news.php");
	$app->mount("/comments", include __DIR__."/Controllers/comments.php");
	$app->mount("/sponsors", include __DIR__."/Controllers/sponsors.php");


	$app->post('/upload/', function(Request $request) use ($app){

		$user_var = $app['session']->get('user_var');

		echo 'upload <br>';
		if($user_var['role'] > 2){
			
			echo '>2 <br>';

			if( null == $request->get('route') ){
				//return $app->redirect( $request->get('route') );
			}else{
				//return $app->redirect( $app['homepage_route'] );
			}	
		}else{
			echo '<2 <br>';

			$uploaddir = __DIR__.'\..\upload\\';
			echo " $uploaddir <br>";

			$uploadfile = $uploaddir . basename($_FILES['userfile']['name']);
			echo " $uploadfile <br>";

			$s = json_encode( $_FILES['userfile'] );

			echo "$s <br>";

			if( null == $request->get('route') ){
				$route = $request->get('route');
			}else{
				$route = $app['homepage_route'];
			}


			if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
				$filename = basename($_FILES['userfile']['name']);
				$filepath = __DIR__.'\..\views\imgsrc\\';
				rename( $upload, $filepath . $filename );    
				//$app['pict']->putPicture( $name, $filepath , $route);
			} else {
			    
			}
			return  $app->redirect(	$route );
		}
		return '';
	});



	$app->get('/about', function() use ($app){

		$names = array('about','aboutproject', 'contacts', 'garant');
		$names_active = array(
			'about'=>'active',
			'aboutproject'=>'', 
			'contacts'=>'', 
			'garant'=>''
			);

	
			$user_var = $app['session']->get('user_var');
			$base_url = $app['homepage_route'];
			$text_url = "/about";
			
			$dir = __DIR__.'/../views/imgsrc';	
			$pics_scan = scandir($dir);
			$pics = array();

			$user_var = $app['session']->get('user_var');

			foreach ($pics_scan as $value) {
				if( $value != '.' && $value != '..'  )
				$pics[] = array('src'=> $value);
			}

			
			return $app['twig']->render('static.html', array(
				'user_var'=>$user_var, 
				"base_url"=>$base_url, 
				"text_url"=>$text_url,
				"names_active"=>$names_active,
				'pics_data'=>json_encode($pics)
				));				
		
	});	
	$app->get('/aboutproject', function() use ($app){

		$names = array('about','aboutproject', 'contacts', 'garant');
		$names_active = array(
			'about'=>'',
			'aboutproject'=>'active', 
			'contacts'=>'', 
			'garant'=>''
			);

			$user_var = $app['session']->get('user_var');
			$base_url = $app['homepage_route'];
			$text_url = "/aboutproject";
			
			return $app['twig']->render('static.html', array(
				'user_var'=>$user_var, "base_url"=>$base_url, 
				"text_url"=>$text_url, "names_active"=>$names_active));				
		
	});	
	$app->get('/contacts', function() use ($app){

		$names = array('about','aboutproject', 'contacts', 'garant');
		$names_active = array(
			'about'=>'',
			'aboutproject'=>'', 
			'contacts'=>'active', 
			'garant'=>''
			);

			$user_var = $app['session']->get('user_var');
			$base_url = $app['homepage_route'];
			$text_url = "/contacts";
			
			return $app['twig']->render('static.html', array(
				'user_var'=>$user_var, "base_url"=>$base_url, 
				"text_url"=>$text_url, "names_active"=>$names_active));				
		
	});	
	
	$app->get('/garant', function() use ($app){

		$names = array('about','aboutproject', 'contacts', 'garant');
		$names_active = array(
			'about'=>'',
			'aboutproject'=>'', 
			'contacts'=>'', 
			'garant'=>'active'
			);

		
			$user_var = $app['session']->get('user_var');
			$base_url = $app['homepage_route'];
			$text_url = "/garant";
			
			return $app['twig']->render('static.html', array(
				'user_var'=>$user_var, "base_url"=>$base_url, 
				"text_url"=>$text_url, "names_active"=>$names_active));				
		
		
	});	
	
	
	

	/**
	example mount
	**/
	/*
	$sapp->mount("/films", include __DIR__."/Controllers/series.php");
	$app->mount("/users", include __DIR__."/Controllers/user.php");
	$app->mount("/usersko", include __DIR__."/Controllers/userko.php");
	*/

	return $app;
?>